<?php
defined('IN_PHPCMS') or exit('No permission resources.');
//模型原型存储路径
define('MODEL_PATH',PC_PATH.'modules'.DIRECTORY_SEPARATOR.'content'.DIRECTORY_SEPARATOR.'fields'.DIRECTORY_SEPARATOR);
//模型缓存路径
define('CACHE_MODEL_PATH',CACHE_PATH.'caches_model'.DIRECTORY_SEPARATOR.'caches_data'.DIRECTORY_SEPARATOR);
pc_base::load_app_class('admin','admin',0);
/**
 * 报名字段管理
 */
class reg extends admin {
	private $db;
	public $siteid;
	function __construct() {
		parent::__construct();
		$this->db = pc_base::load_model('reg_table_info_model');
		$this->table = pc_base::load_model('reg_table_column_model');
		$this->log = pc_base::load_model('reg_log_model');
		$this->talent = pc_base::load_model('talent_model');//加载人才库模型
		$this->talent_source = pc_base::load_model('talent_source_model');//加载人才库关联资源模型
		$this->picture = pc_base::load_model('picture_nsr_model');//加载图集模型
		$this->video = pc_base::load_model('video_nsr_model');//加载视频模型
		$this->siteid = $this->get_siteid();
		if(!$this->siteid) $this->siteid = 1;
	}
	
	/**
	 * 报名列表
	 */
	public function init() {
        //获取管理员真实姓名数据
        $admin_model = pc_base::load_model('admin_model');
        $adminInfo = $admin_model->getRealnameInfo();
		$show_pc_hash = '';
		$where = array('siteid'=>$this->siteid,'status'=>1);
		$page = $_GET['page']?intval($_GET['page']):1;
		if($_SESSION['roleid'] ==1 ) {
			$datas = $this->db->listinfo($where,' id desc',$_GET['page'],15);
			$pages = $this->db->pages;
		} else {
			$sql="select p.* from nsrweb_reg_auth as r LEFT JOIN nsrweb_reg_table_info as p on p.id = r.reg_id where p.status=1 AND r.userid=".$_SESSION['userid'];
			$sql .= " group by p.id order by p.id desc ";
			$datas = $this->db->my_listinfos($sql, $page, 15);
			$pages = $this->db->pages;
		}
		foreach ($datas as $k => $v) {
			$datas[$k]['num'] = $this->table->count(array('table_info_id'=>$v['id'],'status'=>1));
			$sqls = "select count(distinct uniq_id) as nums from nsrweb_reg_log where table_info_id = " . $v['id'];
			$rtn = $this->log->query($sqls);
			$nums = $this->log->fetch_array();
			$datas[$k]['nums'] = $nums[0]['nums'];
		}
		$model_setting=pc_base::load_model('site_setting_model');
		//取报名类型
		$reg_type = $model_setting->getValue("reg_type",$this->siteid);
		$big_menu = array('javascript:window.top.art.dialog({id:\'add\',iframe:\'?m=sign_up&c=reg&a=add\', title:\''.L('add_reg').'\', width:\'580\', height:\'420\', lock:true}, function(){var d = window.top.art.dialog({id:\'add\'}).data.iframe;var form = d.document.getElementById(\'dosubmit\');form.click();return false;}, function(){window.top.art.dialog({id:\'add\'}).close()});void(0);', L('add_reg'));
		include $this->admin_tpl('reg_list');
	}
	
	/**
	 * 添加报名
	 */
	public function add() {
		if(isset($_POST['dosubmit'])) {
			$id = $this->db->edit($_POST['reg']);
			if ($id) {
				//初始化报名字段
				$this->addRegField($id,$_POST['reg']['source_type'],$_POST['reg']['contest_district']);
				//记录行为日志
                $log_content = '<span style="color:#00CC00;">添加报名</span>[新生成报名id：'.$id.'，标题：'.$_POST['reg']['title'].']';
                $this->manage_admin_log($log_content);

				showmessage(L('operation_success'),'?m=sign_up&c=reg','','add');
			} else {
				showmessage(L('operation_failure'), HTTP_REFERER);
			}
		} else {
			//取赛区
			$model_setting=pc_base::load_model('site_setting_model');
			$contest_district = $model_setting->getValue("contest_district",$this->siteid);
			//取报名类型
			$reg_type = $model_setting->getValue("reg_type",$this->siteid);
			pc_base::load_sys_class('form','',0);
			$show_header = $show_validator = '';
			include $this->admin_tpl('reg_add');
		}
	}

	/**
	 * 初始化报名字段
	 */
	public function addRegField ($id,$source_type,$contest_district) {
		//初始化报名管理员配置
		$datas = array();
		if($_SESSION['roleid'] !=1 ) {
			$datas['reg_id'] = $id;
			$datas['contest_district'] = $contest_district;
			$datas['reg_type'] = $source_type;
			$datas['userid'] = $_SESSION['userid'];;
			$datas['siteid'] = $this->siteid;
			$datas['create_time'] =date("Y-m-d H:i:s",time());
			$datas['created_by'] = $_SESSION['userid'];
			$datas['update_time'] =date("Y-m-d H:i:s",time());
			$datas['updated_by'] = $_SESSION['userid'];
			$reg_auth = pc_base::load_model('reg_auth_model');
			$reg_auth->insert($datas,true);
		}
		if ($source_type == 1) {
			$list = $this->table->select(array('table_info_id'=>20,'status'=>1));
		} else if ($source_type == 2) {
			$list = $this->table->select(array('table_info_id'=>12,'status'=>1));
		} else if ($source_type == 3) {
			$list = $this->table->select(array('table_info_id'=>18,'status'=>1));
		} else if ($source_type == 4) {
			$list = $this->table->select(array('table_info_id'=>21,'status'=>1));
		} else if ($source_type == 5) {
			$list = $this->table->select(array('table_info_id'=>13,'status'=>1));
		}
		$data = array();
		foreach ($list as $k => $v) {
			unset($v['id']);
			$v['table_info_id'] = $id;
			$v['create_time'] =date("Y-m-d H:i:s",time());
			$v['created_by'] = $_SESSION['userid'];
			$v['update_time'] =date("Y-m-d H:i:s",time());
			$v['updated_by'] = $_SESSION['userid'];
			$data[$k] = $v;
		}
		$this->table->multiInsert($data);
	}

	/**
	 * 修改报名
	 */
	public function edit() {
		if (!isset($_GET['id']) || empty($_GET['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = intval($_GET['id']);
		if(isset($_POST['dosubmit'])) {
			$id = $this->db->edit($_POST['reg'],$id);
			if ($id) {
				//记录行为日志
                $log_content = '<span style="color:blue;">修改报名</span>[报名id：'.$id.'，标题：'.$_POST['reg']['title'].']';
                $this->manage_admin_log($log_content);

				showmessage(L('operation_success'),'?m=sign_up&c=reg','','edit');
			}
		} else {
			$info = $this->db->get_one(array('id'=>$id));
			//取赛区
			$model_setting=pc_base::load_model('site_setting_model');
			$contest_district = $model_setting->getValue("contest_district",$this->siteid);
			//取报名类型
			$reg_type = $model_setting->getValue("reg_type",$this->siteid);
			pc_base::load_sys_class('form','',0);
			$show_header = $show_validator = '';
			if ($info['source_type'] == 1) {
				$contest_id = $info['source_id'];
			} else if($info['source_type'] == 2) {
				$course_id = $info['source_id'];
			}
			include $this->admin_tpl('reg_edit');
		}
	}

	/**
	 * 删除报名
	 */
	public function delete() {
		if (!isset($_GET['id']) || empty($_GET['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = intval($_GET['id']);
        $info = $this->db->get_one(array('id'=>$id));
        $result = $this->db->edit(array('status'=>2), $id);

        //记录行为日志
        $log_content = '<span style="color:red;">删除报名</span>[报名id：'.$id.'，标题：'.$info['title'].']';
        $this->manage_admin_log($log_content);

        if ($result) {
            showmessage(L('operation_success'), HTTP_REFERER);
        } else {
            showmessage(L("operation_failure"), HTTP_REFERER);
        }
	}

	/**
	 * 报名字段列表
	 */
	public function fields ()
	{
		$id = intval($_GET['id']);
		$info = $this->db->get_one(array('id'=>$id));
		$where = array();
		$where['table_info_id'] = $id;
		$where['status'] = 1;
		$lists = $this->table->select($where,'*','','sort desc,id asc');
		//取报名字段类型配置
		$model_setting=pc_base::load_model('site_setting_model');
		$types = $model_setting->getValue("reg_field_type",$this->siteid);
		$big_menu1 = 'javascript:window.top.art.dialog({id:\'add\',iframe:\'?m=sign_up&c=reg&a=add_field&id='.$id.'\', title:\''.L('add_field').'\', width:\'660\', height:\'420\', lock:true}, function(){var d = window.top.art.dialog({id:\'add\'}).data.iframe;var form = d.document.getElementById(\'dosubmit\');form.click();return false;}, function(){window.top.art.dialog({id:\'add\'}).close()});void(0);';
		include $this->admin_tpl('field_list');
	}

	/**
	 * 添加报名字段
	 */	
	public function add_field ()
	{
		if(isset($_POST['dosubmit'])) {
			$id = $this->table->edit($_POST['field']);
			if ($id) {
				$info = $this->db->get_one(array('id'=>$_POST['field']['table_info_id']));
				//记录行为日志
                $log_content = '<span style="color:#00CC00;">添加报名字段</span>[报名id：'.$info['id'].'，报名标题：'.$info['title'].'，新生成字段id：'.$id.'，字段名：'.$_POST['field']['column_name'].']';
                $this->manage_admin_log($log_content);

				showmessage(L('operation_success'),'?m=sign_up&c=reg&a=fields&id='.$_POST['field']['table_info_id'],'','add');
			} else {
				showmessage(L('operation_failure'), HTTP_REFERER);
			}
		} else {
			//取报名字段类型配置
			$model_setting=pc_base::load_model('site_setting_model');
			$types = $model_setting->getValue("reg_field_type",$this->siteid);
			$table_info_id = intval($_GET['id']);
			pc_base::load_sys_class('form','',0);
			$show_header = $show_validator = '';
			include $this->admin_tpl('field_add');
		}
	}

	/**
	 * 修改报名字段
	 */
	public function edit_field ()
	{
		if (!isset($_GET['id']) || empty($_GET['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = intval($_GET['id']);
		if(isset($_POST['dosubmit'])) {
			$id = $this->table->edit($_POST['field'],$id);
			if ($id) {
				$info = $this->db->get_one(array('id'=>$_POST['field']['table_info_id']));
				//记录行为日志
                $log_content = '<span style="color:blue;">修改报名字段</span>[报名id：'.$info['id'].'，报名标题：'.$info['title'].'，字段id：'.$id.'，字段名：'.$_POST['field']['column_name'].']';
                $this->manage_admin_log($log_content);

				showmessage(L('operation_success'),'?m=sign_up&c=reg&a=fields&id='.$_POST['field']['table_info_id'],'','edit');
			}
		} else {
			//取报名字段类型配置
			$model_setting=pc_base::load_model('site_setting_model');
			$types = $model_setting->getValue("reg_field_type",$this->siteid);
			$info = $this->table->get_one(array('id'=>$id));
			pc_base::load_sys_class('form','',0);
			$show_header = $show_validator = '';
			include $this->admin_tpl('field_edit');
		}
	}

	/**
	 * 删除报名字段
	 */
	public function delete_field ()
	{
		if (!isset($_GET['id']) || empty($_GET['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = intval($_GET['id']);
        $info = $this->table->get_one(array('id'=>$id));
        $resInfo = $this->db->get_one(array('id'=>$info['table_info_id']));
        $result = $this->table->edit(array('status'=>2), $id);

        //记录行为日志
        $log_content = '<span style="color:red;">删除报名字段</span>[报名id：'.$resInfo['id'].'，报名标题：'.$resInfo['title'].'，字段id：'.$info['id'].'，字段名：'.$info['column_name'].']';
        $this->manage_admin_log($log_content);

        if ($result) {
            showmessage(L('operation_success'), HTTP_REFERER);
        } else {
            showmessage(L("operation_failure"), HTTP_REFERER);
        }
	}

	/**
	 * 字段排序
	 */
	public function listorder ()
	{
		if(isset($_POST['dosubmit'])) {
            foreach($_POST['listorders'] as $id => $listorder) {
                $this->table->edit(array('sort'=>$listorder),$id);
            }
            showmessage(L('operation_success'));
        } else {
            showmessage(L('operation_failure'));
        }
	}

	/**
	 * 报名统计
	 */
	public function reg_statistics ()
	{
		if($_SESSION['roleid'] ==1 ) {
			//取赛区
			$model_setting=pc_base::load_model('site_setting_model');
			$district = $model_setting->getValue("contest_district",$this->siteid);
		} else {
			$reg_auth = pc_base::load_model('reg_auth_model');
			$district = $reg_auth->getNoAdminList();
		}
		pc_base::load_sys_class('form','',0);
		$list = $this->db->regList();
		$where = '';
		$page = $_GET['page']?intval($_GET['page']):1;
		$field = $_GET['field'];
		$delete_field = explode('|',$field);
		$count = 20;
		if(isset($_GET['res_id']) && $_GET['res_id']) {
            $where .= ' table_info_id = ' . $_GET['res_id'];
            $tableInfo = $this->table->get_one(array('table_info_id'=>$_GET['res_id'],'column_name'=>'状态'));
            $status_log = explode(',',$tableInfo['column_values']);
        } else {
        	showmessage('请选择报名标题', HTTP_REFERER);
        }
        $uniq_ids = array();
        if ((isset($_GET['district']) && $_GET['district']) || (isset($_GET['username']) && $_GET['username'])) {
        	if ($_GET['district']) {
        		$districts = trim($district[$_GET['district']]);
	        	$districts = substr($districts, 0, -6);
	        	$uniq_id_array1 = $this->log->select(" column_name = '参赛地区' and table_info_id = ".$_GET['res_id']." and user_column_value like '%$districts%' ");
	        	foreach ($uniq_id_array1 as $v) {
	        		$uniq_ids[] = $v['uniq_id'];
	        	}
        	}
        	if ($_GET['username']) {
	        	$username = trim($_GET['username']);
	        	$uniq_id_array2 = $this->log->select(" column_name = '姓名' and table_info_id = ".$_GET['res_id']." and user_column_value like '%$username%' ");
	        	foreach ($uniq_id_array2 as $v) {
	        		$uniq_ids[] = $v['uniq_id'];
	        	}
	        }
    		$uniq_ids = implode('\',\'', $uniq_ids);
    		$where .= " AND uniq_id in ('$uniq_ids') ";
        }
        if(isset($_GET['start_time']) && $_GET['start_time']) {
            $start_time = $_GET['start_time'];
            $where .= $where?" AND `create_time` > '$start_time'":" `create_time` > '$start_time'";
        }
        if(isset($_GET['end_time']) && $_GET['end_time']) {
            $end_time = $_GET['end_time'];
            $where .= $where?" AND `create_time` < '$end_time'":" `create_time` < '$end_time'";
        }
        if ($_GET['export']) {
			$filename = $list[$_GET['res_id']].date('YmdHis');
			//取导出字段列表
	    	$frist =array();
	    	$frist[0] = "编号";
	    	$reg_list = $this->table->select(array('is_show'=>1,'status'=>1,'table_info_id'=>$_GET['res_id']),'column_name','','sort desc,id asc');
	    	foreach ($reg_list as $v) {
	    		$frist[] = $v['column_name'];
	    	}
	    	$frist[] = "报名时间";
	    	$counts = count($frist);
	    	$res_lists = $this->log->select($where,'*','','sort desc,id desc');
	    	$datas = array();
	    	//处理数据生成横表数据
	    	foreach ($res_lists as $k => $v) {
	    		$key = array_search($v['column_name'],$frist);
	    		if (!$datas[$v['uniq_id']][$counts]) {
	    			$datas[$v['uniq_id']][$counts] = $v['create_time'];
	    		}
	    		if (!$datas[$v['uniq_id']][0]) {
	    			$datas[$v['uniq_id']][0] = $v['uniq_id'];
	    		}
	    		if($key){
	    			$datas[$v['uniq_id']][$key] = $v['user_column_value'];
	    		}
	    		ksort($datas[$v['uniq_id']]);
	    	}
	    	//完成导出功能
			exportexcel($datas,$frist,$filename);exit;
		} else {
			//取展示字段列表
	    	$frist =array();
	    	$frist[0] = "编号";
	    	$reg_list = $this->table->select(array('is_accord'=>1,'status'=>1,'table_info_id'=>$_GET['res_id']),'column_name','','sort desc,id asc');
	    	foreach ($reg_list as $v) {
	    		if(!in_array($v['column_name'],$delete_field)){
	    			$frist[] = $v['column_name'];
	    		}
	    	}
	    	$frist[] = "报名时间";
	    	$counts = count($frist);
	    	$frist_count = count($frist); 
	    	$res_lists = $this->log->select($where,'*','','sort desc,id desc');
	    	$datas = array();
	    	//处理数据生成横表数据
	    	foreach ($res_lists as $k => $v) {
	    		$key = array_search($v['column_name'],$frist);
	    		if (!$datas[$v['uniq_id']][$counts]) {
	    			$datas[$v['uniq_id']][$counts] = $v['create_time'];
	    		}
	    		if (!$datas[$v['uniq_id']][0]) {
	    			$datas[$v['uniq_id']][0] = $v['uniq_id'];
	    		}
	    		if($key){
	    			if($v['column_type'] == 7) {
	    				$column_type = explode(',',$v['user_column_value']);
						$column_type = array_filter($column_type);
						$datas[$v['uniq_id']][$key] = empty($column_type)?"<font color='red'>（未设置）</font>":"<img src='".$column_type[0]."' height='60' />";
	    			} else {
	    				$datas[$v['uniq_id']][$key] = $v['user_column_value'];
	    			}
	    		}
	    		ksort($datas[$v['uniq_id']]);
	    	}
	    }
		//数组进行分页
		$totals=count($datas);
        $start = ($page-1)*$count;
        $pagedata=array_slice($datas,$start,$count);
        //var_dump($pagedata);die; 
		$pages = pages($totals, $page, $count);
		include $this->admin_tpl('reg_statistics');
	}

	/**
	 * 单个报名用户详细信息
	 */
	public function log_show ()
	{
		$id = intval($_GET['id']);
		$uniq_id = trim($_GET['uniq_id']);
		//取用户状态信息
		// $statusInfo = $this->log->get_one(array('table_info_id'=>$id,'uniq_id'=>$uniq_id,'column_name'=>'状态'));
		// if(empty($statusInfo)){
		// 	$data = array();
		// 	$data[0]['column_name']='状态';
		// 	$data[1]['column_name']='备注';
  //           $data[1]['table_info_id'] = $data[0]['table_info_id']=$id;
  //           $data[1]['uniq_id'] = $data[0]['uniq_id']=$uniq_id;
  //           $data[0]['user_column_value'] = '未联系';
  //           $data[1]['user_column_value'] = '';
  //           $data[0]['column_type'] = 2;
  //           $data[1]['column_type'] = 3;
  //           $data[1]['create_time'] = $data[0]['create_time'] = date("Y-m-d H:i:s",time());
		// 	//赋值用户初始状态值
		// 	$this->log->multiInsert($data);

		// }
		$datas = $this->log->select(array('table_info_id'=>$id,'uniq_id'=>$uniq_id),'*','','id asc');
		$list = $this->db->regList();
		foreach ($datas as $k => $v) {
			$datas[$k]['table_info_name'] = $list[$v['table_info_id']];
			if ($v['column_type'] == 7 || $v['column_type'] == 5 || $v['column_type'] == 8) {
				$column_type = explode(',',$v['user_column_value']);
				$datas[$k]['user_column_value'] = array_filter($column_type);
			}
		}
		include $this->admin_tpl('log_show');
	}

	/**
	 * 报名用户状态修改
	 */
	public function ajax_log_status ()
	{
		$uniq_id = trim($_POST['uniq_id']);
		$status = trim($_POST['status']);
		$info = $this->log->get_one(array('uniq_id'=>$uniq_id,'column_name'=>'状态'));
		$res = $this->log->update(array('user_column_value'=>$status),array('uniq_id'=>$uniq_id,'column_name'=>'状态'));
		$infos = $this->db->get_one(array('id'=>$info['table_info_id']));
		if ($res) {
			//记录行为日志
            $log_content = '<span style="color:blue;">修改用户信息状态</span>[报名id：'.$infos['id'].'，报名标题：'.$infos['title'].'，用户信息id:'.$info['id'].'，用户信息名：状态，用户信息值：'.$status.']';
            $this->manage_admin_log($log_content);
			echo '1';die;
		} else {
			echo '0';die;
		}
	}

	/**
	 * 报名用户信息修改
	 */
	public function reg_log_edit ()
	{
		if (!isset($_GET['id']) || empty($_GET['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = intval($_GET['id']);
        $info = $this->log->get_one(array('id'=>$id));
		$regInfo = $this->table->get_one(array('table_info_id'=>$info['table_info_id'],'column_name'=>$info['column_name']));
		if(isset($_POST['dosubmit'])) {
			if($regInfo['column_type' == 6]){
				$user_column_value = implode(',',$_POST['user_column_value']);
			} else {
				$user_column_value = $_POST['user_column_value'];
			}
			$id = $this->log->update(array('user_column_value'=>$user_column_value),array('id'=>$id));
			if ($id) {
				$infos = $this->db->get_one(array('id'=>$info['table_info_id']));
				//记录行为日志
                $log_content = '<span style="color:blue;">修改报名用户信息</span>[报名id：'.$infos['id'].'，报名标题：'.$infos['title'].'，用户信息id:'.$info['id'].'，用户信息名：'.$info['column_name'].'，用户信息值：'.$user_column_value.']';
                $this->manage_admin_log($log_content);

				showmessage(L('operation_success'),'?m=sign_up&c=reg&a=log_show&id='.$info['table_info_id'].'&uniq_id='.$info['uniq_id'],'','edit');
			} else {
				showmessage(L("operation_failure"), HTTP_REFERER);
			}
		} else {
			$column_values = explode(',',$regInfo['column_values']);
			$user_column_value = explode(',',$info['user_column_value']);
			pc_base::load_sys_class('form','',0);
			$show_header = $show_validator = '';
			include $this->admin_tpl('reg_log_edit');
		}
	}

	/**
	 * 报名权限设置
	 */
	public function reg_power ()
	{
		$where = '';
		$reg_auth = pc_base::load_model('reg_auth_model');
		$datas = $reg_auth->listinfo($where,' id desc',$_GET['page'],20);
		$pages = $reg_auth->pages;
		//获取管理员真实姓名数据
        $admin_model = pc_base::load_model('admin_model');
        $adminInfo = $admin_model->getRealnameInfo();
		//取赛区
		$model_setting=pc_base::load_model('site_setting_model');
		$contest_district = $model_setting->getValue("contest_district",$this->siteid);
		//取报名类型
		$reg_type = $model_setting->getValue("reg_type",$this->siteid);
		//取报名
		$regList = $this->db->regList();
		$big_menu = array('javascript:window.top.art.dialog({id:\'add\',iframe:\'?m=sign_up&c=reg&a=add_reg_power\', title:\''.L('add_reg_power').'\', width:\'580\', height:\'220\', lock:true}, function(){var d = window.top.art.dialog({id:\'add\'}).data.iframe;var form = d.document.getElementById(\'dosubmit\');form.click();return false;}, function(){window.top.art.dialog({id:\'add\'}).close()});void(0);', L('add_reg_power'));
		include $this->admin_tpl('reg_power');
	}

	/**
	 * 添加报名设置
	 */
	public function add_reg_power ()
	{
		$reg_auth = pc_base::load_model('reg_auth_model');
		if(isset($_POST['dosubmit'])) {
			$data = array();
			//获取管理员真实姓名数据
	        $admin_model = pc_base::load_model('admin_model');
	        $adminInfo = $admin_model->getRealnameInfo();
			$info = $this->db->get_one(array('id'=>$_POST['reg_id']));
			$username = '';
			$userauth = '';
			foreach ($_POST['user_id'] as $k => $v) {
				$authInfo = $reg_auth->get_one(array('reg_id'=>$_POST['reg_id'],'userid'=>$v));
				if (empty($authInfo)) {
					$data[$k]['reg_id'] = $_POST['reg_id'];
					$data[$k]['contest_district'] = $info['contest_district'];
					$data[$k]['reg_type'] = $info['source_type'];
					$data[$k]['userid'] = $v;
					$data[$k]['siteid'] = $this->siteid;
					$data[$k]['create_time'] =date("Y-m-d H:i:s",time());
					$data[$k]['created_by'] = $_SESSION['userid'];
					$data[$k]['update_time'] =date("Y-m-d H:i:s",time());
					$data[$k]['updated_by'] = $_SESSION['userid'];
					$username .=  $username?','.$adminInfo[$v]:$adminInfo[$v];
				} else {
					$userauth = $username?','.$adminInfo[$v]:$adminInfo[$v];;
				}
			}
			if(!empty($data)){
				$res = $reg_auth->multiInsert($data);
			}
			if ($res) {
				//记录行为日志
                $log_content = '<span style="color:#00CC00;">添加报名配置</span>[报名id：'.$_POST['reg_id'].'，标题：'.$info['title'].'与管理员的绑定('.$username.')，已绑定的管理员('.$userauth.')]';
                $this->manage_admin_log($log_content);

				showmessage(L('operation_success'),'?m=sign_up&c=reg&a=reg_power','','add');
			} else {
				showmessage(L('operation_failure'), HTTP_REFERER);
			}
		} else {
			//取赛区
			$model_setting=pc_base::load_model('site_setting_model');
			$contest_district = $model_setting->getValue("contest_district",$this->siteid);
			//取报名类型
			$reg_type = $model_setting->getValue("reg_type",$this->siteid);
			//取报名
			$regList = $this->db->regList();
			//取绑定管理员
			$model_setting=pc_base::load_model('site_setting_model');
			$rolelist = $model_setting->getValue("role_user",$this->siteid);
			$role = array();
			foreach ($rolelist as $k => $v) {
				$admin_model = pc_base::load_model('admin_model');
				$admin_role_model = pc_base::load_model('admin_role_model');
				$info = $admin_role_model->get_one(array('roleid'=>$v));
				$role[$v]['user_list'] = $admin_model->select(array('roleid'=>$v));
				$role[$v]['name'] = $info['rolename'];
			}
			pc_base::load_sys_class('form','',0);
			$show_header = $show_validator = '';
			include $this->admin_tpl('power_add');
		}
	}

	/**
	 * ajax 获取报名、赛区
	 */
	public function ajax_reg_district ()
	{
		$where = array();
		$where['status'] = 1;
		$where['siteid'] = $this->siteid;
		$reg_type = $_POST['reg_type']?intval($_POST['reg_type']):'';
		$district = $_POST['district']?intval($_POST['district']):'';
		$type = $_POST['type']?intval($_POST['type']):0;
		//取赛区
		$model_setting=pc_base::load_model('site_setting_model');
		$contest_district = $model_setting->getValue("contest_district",$this->siteid);
		$data = array();
		if ($_POST['status'] == 1) {
			if($_SESSION['roleid'] ==1) {
				$lists = $this->db->select(array('contest_district'=>$district,'status'=>1,'siteid'=>$this->siteid));
			} else {
				//取报名
				$reg_list = $division_list = array();
				$reg_auth = pc_base::load_model('reg_auth_model');
				$list = $reg_auth->select(array('contest_district'=>$district,'userid'=>$_SESSION['userid']));
				$lists = array();
				foreach ($list as $k => $v) {
					$lists[$k]['id'] = $v['reg_id'];
					$lists[$k]['title'] = $reg_list[$v['reg_id']];
				}
			}
			$data['list'] = $lists;
			$data['status'] = 200;
			echo json_encode($data);die;
		}
		if ($type) {
			//取报名
			$reg_list = $division_list = array();
			$where['source_type'] = $reg_type;
			$list = $this->db->select($where);
			foreach ($list as $k => $v) {
				$reg_list[$k]['id'] = $v['id'];
				$reg_list[$k]['title'] = $v['title'];
				if ($v['contest_district']) {
					$division_list[$v['contest_district']] = $contest_district[$v['contest_district']];
				}
			}
			ksort($division_list);
			$data['reg_list'] = $reg_list;
			$data['division_list'] = $division_list;
			$data['status'] = 200;
			echo json_encode($data);die;
		} else {
			if ($reg_type) {
				$where['source_type'] = $reg_type;
			}
			$where['contest_district'] = $district;
			$list = $this->db->select($where);
			$data['list'] = $list;
			$data['status'] = 200;
			echo json_encode($data);die;
		}
	}

	/**
	 * 删除报名设置
	 */
	public function del_reg_power ()
	{
        //取报名
		$regList = $this->db->regList();
		//获取管理员真实姓名数据
        $admin_model = pc_base::load_model('admin_model');
        $adminInfo = $admin_model->getRealnameInfo();
        $reg_auth = pc_base::load_model('reg_auth_model');
        if (! isset($_REQUEST['id']) || empty($_REQUEST['id'])) {
            showmessage(L('illegal_action'), HTTP_REFERER);
        }
        $id = $_REQUEST['id'];
        $str = '';
        if (is_array($id)) {
            foreach ($id as $k => $v) {
                if (intval($v)) {
                    $info = $reg_auth->get_one(array('id'=>$v));
                    $str .= ($str?'、':'').'删除报名(id:'.$info['reg_id'].',标题：'.$regList[$info['reg_id']].')和管理员(id:'.$info['userid'].',真实姓名:'.$adminInfo[$info['userid']].')配置';
                } else {
                    unset($id[$k]);
                }
            }
            $id = implode('\',\'', $id);
        } else {
            $info = $reg_auth->get_one(array('id'=>$id));
            $str .= '删除报名(id:'.$info['reg_id'].',标题：'.$regList[$info['reg_id']].')和管理员(id:'.$info['userid'].',真实姓名:'.$adminInfo[$info['userid']].')配置';
        }
        $result = $reg_auth->delete("id in ('$id')");

        //记录行为日志
        $log_content = '<span style="color:red;">删除报名配置</span>['.$str.']';
        $this->manage_admin_log($log_content);

        if ($result) {
            showmessage(L('operation_success'), HTTP_REFERER);
        } else {
            showmessage(L('operation_failure'), HTTP_REFERER);
        }
	}
	
	/**
	 * 报名信息导入人才库
	 */
	public function handle() {
		pc_base::load_app_func('getFirstCharter','sign_up');
		$where = "";
		$id = $_GET['id'];//报名id
		$uniq_id = $_GET['uniq_id'];//报名编号
		$entry_form = $this->db->get_one(array('id'=>$id));//查询报名主题信息
		$where .= "table_info_id = ".$id." and uniq_id = '$uniq_id'";
		$info = $this->log->select($where);
		$reg_info = array();
		foreach ($info as $k=>$v){
			$reg_info[$v['column_name_en']] = $v['user_column_value'];
		}
		if ($reg_info['status'] == '已导入'){
			showmessage('已导入人才库，不可重复导入');
		} else{
			//写入人才信息
			$talent_info = array();
			$talent_info['real_name'] = $reg_info['real_name'];//姓名
			$talent_info['age'] = $reg_info['age'];//年龄
			$talent_info['talent_type'] = array('is_network');//选手
			if ($reg_info['gender'] == '男') {
				$talent_info['gender'] = 1;//性别
			} elseif ($reg_info['gender'] == '女'){
				$talent_info['gender'] = 2;
			} else{
				$talent_info['gender'] = 3;
			}
			$talent_info['height'] = $reg_info['height'];//身高
			$talent_info['weight'] = $reg_info['weight'];//体重
			$talent_info['telephone'] = $reg_info['telephone'];//手机号
			$talent_info['introduction'] = $reg_info['introduction'];//个人简介
			$talent_info['source'] = '报名主题ID：'.$id.'，报名主题：'.$entry_form['title'];
			$talent_info['letter'] = getFirstCharter($reg_info['real_name']);
			//报名图集信息不为空，写入图集信息
			if(isset($reg_info['pictureurls']) && !empty($reg_info['pictureurls'])){
				$pictrue_info = array_filter(explode(',', $reg_info['pictureurls']));
				$pictrueurl = array();
				foreach ($pictrue_info as $k=>$v){
					$pictrueurl[$k]['url'] = $v;
					$pictrueurl[$k]['alt'] = '';
				}
				$picture_data = array();
				$picture_data['title'] = $entry_form['title'].$reg_info['real_name'].'图集';
				$picture_data['source_name'] = '新丝路时尚';
				$picture_data['image_cover'] = $pictrue_info[0];
				$picture_result = $this->picture->check($picture_data,'add');
				$picture_result['pictureurls'] = json_encode($pictrueurl,JSON_UNESCAPED_SLASHES);
				$picture_result['source'] = 1;
				$picture_id = $this->picture->edit($picture_result);//图集信息写入图集表
			}
			//报名视频集信息不为空，写入视频集信息
			if (isset($reg_info['video']) && !empty($reg_info['video'])) {
				$video_info = array_filter(explode(',', $reg_info['video']));
				$videos = array();
				$video_title = array();
				$video_id = array();
				foreach ($video_info as $k=>$v){
					if (count($video_info) == 1) {
						$videos['title'] = $entry_form['title'].$reg_info['real_name'].'视频';
					} elseif (count($video_info) > 1) {
						$videos['title'] = $entry_form['title'].$reg_info['real_name'].'视频'.$this->chinanum($k+1);
					}
					$video_title[] = $videos['title'];//视频标题写入日志
					$videos['video_link'] = $v;
					$videos['source_name'] = '新丝路时尚';
					$video_result = $this->video->check($videos,'add');
					$video_result['source'] = 1;
					$video_id[] = $this->video->edit($video_result);//视频信息写入视频表
				}

			}
			$result = $this->talent->moter_add($talent_info,0,'import');//人才信息写入人才表
			if($result){
				//记录行为日志
				$log_content = "";
				$log_content .= '<span style="color:blue;">报名信息导入人才表</span>[人才id：'.$result.'，姓名：'.$talent_info['real_name'].']<br>';
				if (isset($picture_id)){
					$talent_pic_res = $this->talent_pic($result, $picture_id);
					$log_content .= '<span style="color:blue;">报名信息图片导入图片表</span>[图集id：'.$picture_id.'，标题：'.$picture_data['title'].']<br>';
					if (!$talent_pic_res) {
						showmessage('导入失败',HTTP_REFERER);
					}
				}
				if (isset($video_id)) {
					$talent_video_res = $this->talent_video($result, $video_id);
					$log_content .= '<span style="color:blue;">报名信息视频导入视频表</span>[视频id：'.json_encode($video_id).'，标题：'.json_encode($video_title,JSON_UNESCAPED_UNICODE).']<br>';
					if (!$talent_video_res) {
						showmessage('导入失败',HTTP_REFERER);
					}
				}
				$this->manage_admin_log($log_content);
				$reg_log_result = $this->log->update("user_column_value = '已导入'",array('table_info_id'=>$id,'uniq_id'=>$uniq_id,'column_name_en'=>'status'));
				if($reg_log_result){
					showmessage('导入成功','?m=sign_up&c=reg&a=reg_statistics&res_id='.$id);
				} else {
					showmessage('导入失败',HTTP_REFERER);
				}
			} else {
				showmessage('导入失败',HTTP_REFERER);
			}
		}
	}
	
	/**
	 * 报名信息一键导入人才库
	 */
	public function handle_all() {
		pc_base::load_app_func('getFirstCharter','sign_up');
		$where = "";
		$id = $_GET['id'];//报名id
		$entry_form = $this->db->get_one(array('id'=>$id));//查询报名主题信息
		$where .= "table_info_id = ".$id;
		$info = $this->log->select($where);//获取所有的报名信息
		$where .= " and column_name = '状态'";
		$status = $this->log->select($where);//获取报名信息状态
		$status_arr = array();
		foreach ($status as $sv) {
			if ($sv['user_column_value'] != '已导入') {
				$status_arr[] = $sv['uniq_id'];//查找未导入的uniq_id
				
			}
		}
		$reg_info = array();
		//报名uniq_id再未导入的uniq_id组中，进行数据重组
		foreach ($info as $k=>$v){
			if (in_array($v['uniq_id'], $status_arr)) {
				$reg_info[$v['uniq_id']][$v['column_name_en']] = $v['user_column_value'];
				$reg_info[$v['uniq_id']]['uniq_id'] = $v['uniq_id'];
				
			}
		}
		if (empty($reg_info) || count($reg_info) == 0) {
			showmessage('信息已全部导入','?m=sign_up&c=reg&a=reg_statistics&res_id='.$id);
		}
		//记录行为日志
		$log_content = "";
		foreach ($reg_info as $ks=>$vs){
			$uniq_id = $vs['uniq_id'];
			$talent_all_info['real_name'] = $reg_info[$ks]['real_name'];//姓名
			$talent_all_info['age'] = $reg_info[$ks]['age'];//年龄
			$talent_all_info['talent_type'] = array('is_network');//选手
			if ($reg_info[$ks]['gender'] == '男') {
				$talent_all_info['gender'] = 1;//性别
			} elseif ($reg_info[$ks]['gender'] == '女'){
				$talent_all_info['gender'] = 2;
			} else{
				$talent_all_info['gender'] = 3;
			}
			$talent_all_info['height'] = $reg_info[$ks]['height'];//身高
			$talent_all_info['weight'] = $reg_info[$ks]['weight'];//体重
			$talent_all_info['telephone'] = $reg_info[$ks]['telephone'];//手机号
			$talent_all_info['introduction'] = $reg_info[$ks]['introduction'];//个人简介
			$talent_all_info['source'] = '报名主题ID：'.$id.'，报名主题：'.$entry_form['title'];
			$talent_all_info['letter'] = getFirstCharter($reg_info[$ks]['real_name']);
			$talent_result = $this->talent->moter_add($talent_all_info,0,'import');//人才信息写入人才表
			$log_content .= '<span style="color:blue;">报名信息导入</span>[报名id：'.$id.'报名主题：'.$entry_form['title'].'，选手姓名：'.$talent_all_info['real_name'].']<br>';
			if (!$talent_result) {
				showmessage('导入失败',HTTP_REFERER);
			}
			//报名图集信息不为空，写入图集信息
			if(isset($reg_info[$ks]['pictureurls']) && !empty($reg_info[$ks]['pictureurls'])){
				$pictrue_info = array_filter(explode(',', $reg_info[$ks]['pictureurls']));
				$pictrueurl = array();
				foreach ($pictrue_info as $k=>$v){
					$pictrueurl[$k]['url'] = $v;
					$pictrueurl[$k]['alt'] = '';
				}
				$picture_data = array();
				$picture_data['title'] = $entry_form['title'].$reg_info[$ks]['real_name'].'图集';
				$picture_data['source_name'] = '新丝路时尚';
				$picture_data['image_cover'] = $pictrue_info[0];
				$picture_result = $this->picture->check($picture_data,'add');
				$picture_result['pictureurls'] = json_encode($pictrueurl,JSON_UNESCAPED_SLASHES);
				$picture_result['source'] = 1;
				$picture_id = $this->picture->edit($picture_result);//图集信息写入图集表
				if (!$picture_id) {
					showmessage('导入失败',HTTP_REFERER);
				}
				$talent_pic_res = $this->talent_pic($talent_result, $picture_id);
			}
			//报名视频集信息不为空，写入视频集信息
			if (isset($reg_info[$ks]['video']) && !empty($reg_info[$ks]['video'])) {
				$video_info = array_filter(explode(',', $reg_info[$ks]['video']));
				$videos = array();
				$video_title = array();
				$video_id = array();
				foreach ($video_info as $k=>$v){
					if (count($video_info) == 1) {
						$videos['title'] = $entry_form['title'].$reg_info[$ks]['real_name'].'视频';
					} elseif (count($video_info) > 1) {
						$videos['title'] = $entry_form['title'].$reg_info[$ks]['real_name'].'视频'.$this->chinanum($k+1);
					}
					$video_title[] = $videos['title'];//视频标题写入日志
					$videos['video_link'] = $v;
					$videos['source_name'] = '新丝路时尚';
					$video_result = $this->video->check($videos,'add');
					$video_result['source'] = 1;
					$video_id[] = $this->video->edit($video_result);//视频信息写入视频表
				}
				if (!$video_id) {
					showmessage('导入失败',HTTP_REFERER);
				}
				$talent_video_res = $this->talent_video($talent_result, $video_id);
				
			}
			$reg_log_result = $this->log->update("user_column_value = '已导入'",array('table_info_id'=>$id,'uniq_id'=>$uniq_id,'column_name_en'=>'status'));
		}
		$this->manage_admin_log($log_content);
		showmessage('导入成功','?m=sign_up&c=reg&a=reg_statistics&res_id='.$id);
	}
	
	/**
	 * 导入的人才绑定图集
	 */
	public function talent_pic($talent_id,$pic_id,$source_type = 3){
		$data=array();
		$data['talent_id']=$talent_id;
		$data['source_id']=$pic_id;
		$data['source_type']=$source_type;
		$data['is_top']=0;
		$data['sort']=0;
		$data['created_by'] =  $_SESSION['userid'];
		$data['updated_by'] =  $_SESSION['userid'];
		
		$data['create_time'] = date("Y-m-d H:i:s",time());
		$data['update_time'] = date("Y-m-d H:i:s",time());
			
		$result = $this->talent_source->insert($data);
		return $result;
	}
	
	/**
	 * 导入的人才绑定视频
	 */
	public function talent_video($talent_id,$video_id,$source_type = 2){
		$data=array();
		$data['talent_id']=$talent_id;
// 		$data['source_id']=$video_id;
		$data['source_type']=$source_type;
		$data['is_top']=0;
		$data['sort']=0;
		$data['created_by'] =  $_SESSION['userid'];
		$data['updated_by'] =  $_SESSION['userid'];
		
		$data['create_time'] = date("Y-m-d H:i:s",time());
		$data['update_time'] = date("Y-m-d H:i:s",time());
		if (is_array($video_id)) {
			foreach ($video_id as $v){
				$data['source_id']= $v;
				$result = $this->talent_source->insert($data);
			}
		}
		return $result;
	}
	
	/**
	 * 生成二维码
	 */
	public function qrcode() {
		$url = $_GET['url'];
		$show_header = false;
		include $this->admin_tpl('qrcode');
	}
	
	/**
	 * 数字转汉字
	 */
	public function chinanum($num){
		$china=array('零','一','二','三','四','五','六','七','八','九');
		$arr=str_split($num);
		for($i=0;$i<count($arr);$i++){
			return $china[$arr[$i]];
		}
	}

}